/*
  Copyright 2009 Colin Prinn

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package net.recursv.motific.pool;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Vector;

/**
 * Created by: recursv
 * Date: 31/07/2009
 * Time: 5:22:07 PM
 */
public class DirectoryInputPool implements InputPool {

    protected final File _rootDirectory;

    protected final Vector<String> _files = new Vector<String>();

    public DirectoryInputPool(File directory) throws IOException {
        _rootDirectory = directory;
        initFiles(directory);
    }

    public int size() {
        return _files.size();
    }

    public String getFilename(int index) {
        return _files.get(index);
    }

    private void initFiles(File directory) throws IOException {
        File[] files = directory.listFiles();

        if (files != null) {
            String rootPath = _rootDirectory.getCanonicalPath();

            for (File file : files) {
                if (file.isDirectory()) {
                    initFiles(file);
                } else if (file.isFile()) {
                    String className = file.getCanonicalPath().substring(rootPath.length());
                    if (className.startsWith(File.separator)) {
                        className = className.substring(1);
                    }
                    _files.add(className);
                }
            }
        }
    }

    public URL getURL(int index) throws IOException {
        return new File(_rootDirectory, getFilename(index)).toURI().toURL();
    }
}
